from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver

from apps.CanvasElementManagement.models import CanvasElement
from apps.CanvasElementManagement.serializers import CanvasElementSerializer
from apps.CanvasesManagement.models import Canvas
from apps.CanvasesManagement.serializers import CanvasSerializer
from apps.HistoryManagement.models import ProjectHistory
from apps.LayerManagement.models import LayerGroup
from apps.LayerManagement.serializers import LayerGroupSerializer
from apps.ProjectsManagement.models import Project
from apps.ProjectsManagement.serializers import ProjectSerializer


class HistoryService:
    MAX_HISTORY_COUNT = 100

    @staticmethod
    def create_history(project_id, parent_id=None):
        """创建历史记录"""
        project = Project.objects.get(id=project_id)

        # 获取当前快照
        project_data = ProjectSerializer(project).data
        canvas_data = CanvasSerializer(Canvas.objects.filter(project=project), many=True).data
        element_data = CanvasElementSerializer(CanvasElement.objects.filter(canvas__project_id=project_id),
                                               many=True).data
        layer_data = LayerGroupSerializer(LayerGroup.objects.filter(canvas__project_id=project_id), many=True).data

        # 检查历史记录数量限制
        history_count = ProjectHistory.objects.filter(project_id=project_id).count()
        if history_count >= HistoryService.MAX_HISTORY_COUNT:
            oldest = ProjectHistory.objects.filter(project_id=project_id).earliest('created_at')
            oldest.delete()

        # 创建新的历史记录
        history = ProjectHistory.objects.create(
            project=project,
            parent_id=parent_id,
            project_snapshot=project_data,
            canvas_snapshot=canvas_data,
            element_snapshot=element_data,
            layer_snapshot=layer_data,
            is_current=True
        )

        # 更新之前的current状态
        ProjectHistory.objects.filter(project_id=project_id).exclude(id=history.id).update(is_current=False)
        return history


# @receiver([post_save, post_delete], sender=Project)
# @receiver([post_save, post_delete], sender=Canvas)
# @receiver([post_save, post_delete], sender=CanvasElement)
# @receiver([post_save, post_delete], sender=LayerGroup)
#TODO: 改为监听视图层
def handle_model_changes(sender, instance, **kwargs):
    if sender == Project:
        project_id = instance.id
    elif sender == Canvas:
        project_id = instance.project.id if hasattr(instance, 'project') else None
    elif sender == CanvasElement:
        project_id = instance.canvas.project.id if hasattr(instance, 'canvas') else None
    elif sender == LayerGroup:
        project_id = instance.canvas.project.id if hasattr(instance, 'canvas') else None
    else:
        return

    HistoryService.create_history(project_id)